package com.sanhuo.security;

import com.alibaba.fastjson.JSON;
import com.sanhuo.lib.exception.GlobalException;
import com.sanhuo.security.global.Response;
import com.sanhuo.security.global.ResponseEnum;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.StringUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

@ControllerAdvice
public class GlobalExcetionCatch {

    private static Logger log = Logger.getLogger(GlobalExcetionCatch.class.getName());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response defaultException(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        return new Response(ResponseEnum.EXCEPTION.getCode(), ResponseEnum.EXCEPTION.getMsg());
    }

    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public Object exceptionCatch(HttpServletRequest request, GlobalException e) {
        e.printStackTrace();
//        log.warning(e.getMessage());
        Integer code = e.getCode();
//        + "form : [" + request.getRequestURI() + " ] "
        String message = e.getMessage()  ;
        if (BeanUtil.isNull(code)) {
            code = ResponseEnum.EXCEPTION.getCode();
        }
        if (StringUtil.isBlank(message)) {
            message = ResponseEnum.EXCEPTION.getMsg() + "form : [" + request.getRequestURI() + " ] ";
        }
        if (code == ResponseEnum.INDEX_VERIFY_FAILE.getCode()) {
            ModelAndView modelAndView = new ModelAndView("forward:/");
            modelAndView.addObject("data", JSON.toJSON(new Response(code, message)));
            return modelAndView;
        }
        return new Response(code, message);
    }


}